<style lang="less" scoped>
.hy-point {
  width: 100%;
  height: 100%;
  .shaixuan {
    display: flex;
    align-items: center;
    justify-content: end;
    background: #fff;
    padding: 5px;
    img {
      height: 20px;
    }
  }
  /deep/.el-table__inner-wrapper {
    height: 100% !important;
  }
  .pagination-css {
    padding: 5px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    justify-content: right;
    margin-top: 5px;
  }
}
</style>

<template>
  <div class="hy-point">
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline form-css"
    >
      <el-form-item label="关键字：">
        <el-input
          v-model="formInline.keyword"
          placeholder="请输入条码、姓名、设备名称"
        />
      </el-form-item>
      <el-form-item label="检查时间：">
        <el-date-picker
          v-model="formInline.inspectionTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="报告时间：">
        <el-date-picker
          v-model="formInline.reportTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="质控日期：">
        <el-date-picker
          v-model="formInline.qualityTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="项目点名称：">      
        <el-select
          v-model="formInline.projectName"
          placeholder="请输入项目点名称"
          filterable
        >
          <el-option
            v-for="(item, index) in organNameList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检查医师：">
        <el-input
          v-model="formInline.inspectDoctor"
          placeholder="请输入检查医师"
        />
      </el-form-item>
      <el-form-item label="报告医师：">
        <el-input
          v-model="formInline.reportDoctor"
          placeholder="请输入报告医师"
        />
      </el-form-item>
      <el-form-item label="报告状态：">
        <el-select v-model="formInline.reportStatus" placeholder="请选择">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有效：">
        <el-select v-model="formInline.isInvalid" placeholder="请选择">
          <el-option
            v-for="item in isUsedList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否阳性：">
        <el-select v-model="formInline.isPositive" placeholder="请选择">
          <el-option
            v-for="item in isPositiveList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="search"
          ><el-icon style="margin-right: 6px"><Search /></el-icon>
          搜索</el-button
        >
        <el-button @click="reset"
          ><el-icon style="margin-right: 6px"><Refresh /></el-icon>
          重置</el-button
        >
        <vue3-json-excel
          v-if="roleInfo != 13"
          :fields="json_fields"
          :name="userExcelName"
          :fetch="downloadEx"
          style="margin-left: 12px"
        >
          <el-button>
            <!-- <el-icon style="margin-right: 6px"><Document /></el-icon> -->
            <img
              style="margin-right: 6px; width: 12px"
              src="@/images/daochu.png"
              alt=""
            />

            导出</el-button
          >
        </vue3-json-excel>
        <!-- 9月25号测试 -->
        <el-button type="primary" @click="exportSelectedPDFs">
      批量导出
    </el-button>
      </el-form-item>
    </el-form>
    <div class="filter-column">
      <el-popover
        placement="bottom"
        title="筛选条件"
        :width="150"
        trigger="click"
      >
        <el-checkbox-group v-model="filtrateList" @change="changeBox">
          <!-- <el-checkbox label="t_sn">条码</el-checkbox> -->
          <el-checkbox label="insname">项目点名称</el-checkbox>
          <el-checkbox label="name">姓名</el-checkbox>
          <el-checkbox label="sex">性别</el-checkbox>
          <el-checkbox label="age">年龄</el-checkbox>
          <el-checkbox label="tel">联系电话</el-checkbox>
          <el-checkbox label="diagnostic">诊断结论</el-checkbox>
          <el-checkbox label="isPositive">是否阳性</el-checkbox>
          <el-checkbox label="isInvalid">是否有效</el-checkbox>
          <el-checkbox label="invalidReason">无效原因</el-checkbox>
          <el-checkbox label="devname">设备名称</el-checkbox>
          <el-checkbox label="auditstatus">报告状态</el-checkbox>
          <el-checkbox label="dicomurl">常规报告</el-checkbox>
          <el-checkbox label="checkTime">检查时间</el-checkbox>
          <el-checkbox label="docname">检查医师</el-checkbox>
          <el-checkbox label="reportTime">报告时间</el-checkbox>
          <el-checkbox label="reportDoctor">报告医师</el-checkbox>
          <el-checkbox label="qualityTime">质控日期</el-checkbox>
          <el-checkbox label="medicalRecordID">病历记录ID</el-checkbox>
          <el-checkbox label="devid">设备SN</el-checkbox>
        </el-checkbox-group>
        <template #reference>
          <el-button type="text"
            ><div class="shaixuan">
              <img src="@/images/shaixuan.png" alt="" /> 筛选列
            </div></el-button
          >
        </template>
      </el-popover>
    </div>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      :header-cell-style="{ backgroundColor: '#EEF6FF' }"
      stripe
      border
      height="calc(100% - 324px)"
      style="width: 100%; padding: 10px"
      @selection-change="handleSelectionChange"    
    >
    <!-- 9月25号 添加的@selection-change="handleSelectionChange"，不行就删除-->
    <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="项目点名称" width="120"></el-table-column>
      <el-table-column prop="pdfUrl" label="常规报告" width="150">
        <template #default="scope">
          <a :href="scope.row.pdfUrl" target="_blank">查看报告</a>
        </template>
      </el-table-column>
    <!-- 添加代码的分隔符号9月25号 -->
      <el-table-column type="index" width="50" align="center" />
      <el-table-column
        prop="t_sn"
        min-width="120px"
        label="条码"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        v-if="filtrateList.includes('insname')"
        prop="insname"
        min-width="120px"
        label="项目点名称"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('name')"
        prop="name"
        min-width="90px"
        label="姓名"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('sex')"
        prop="sex"
        min-width="80px"
        label="性别"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('age')"
        prop="age"
        min-width="80px"
        label="年龄"
        align="center"
      >
        <template #default="{ row }">
          <span>{{ row.age == 0 ? "-" : row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('tel')"
        prop="tel"
        min-width="120px"
        label="联系电话"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('diagnostic')"
        prop="diagnostic"
        min-width="160px"
        label="诊断结论"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('isPositive')"
        prop="isPositive"
        min-width="160px"
        label="是否阳性"
        align="center"
      >
        <template #default="{ row }">
          <span>{{
            row.isPositive == "1" ? "阳性" : row.isPositive == "0" ? "阴性" : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('isInvalid')"
        prop="isInvalid"
        min-width="160px"
        label="是否有效"
        align="center"
      >
        <template #header>
          <el-popover
            placement="bottom-start"
            title="提示"
            :width="300"
            trigger="hover"
            content="“无效”表示扫查结果不合格，无法出具报告，需要重新扫查，请等待处理"
          >
            <template #reference>
              <span
                >是否有效<el-icon style="color: rgb(66, 206, 206)"
                  ><WarningFilled /></el-icon
              ></span>
            </template>
          </el-popover>
        </template>
        <template #default="{ row }">
          <span :style="{ color: row.isInvalid == '1' ? 'red' : '' }">{{
            row.isInvalid == 1 ? "无效" : "有效"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('invalidReason')"
        prop="invalidReason"
        min-width="120px"
        label="无效原因"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('devname')"
        prop="devname"
        min-width="120px"
        label="设备名称"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('auditstatus')"
        prop="auditstatus"
        min-width="84px"
        label="报告状态"
        align="center"
      >
        <template #default="{ row }">
          <span>{{
            row.auditstatus == 11
              ? "发送成功"
              : row.auditstatus == 12
              ? "发送失败"
              : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('dicomurl')"
        prop="dicomurl"
        min-width="185px"
        label="常规报告"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            text="primary"
            @click="regularInfo(row)"
            :style="{
              color: (row.dwncnt == 0 || !row.dwncnt) ? ''
                    : '#24ae24',
            }"
            >{{ (row.dwncnt == 0 || !row.dwncnt) ? "下载" : "已下载" }}</el-button
          >
          <el-button
            type="primary"
            text="primary"
            @click="printInfo(row)"
            :style="{
              color: (row.prtcnt == 0 || !row.prtcnt) ? ''
                    : '#24ae24',
            }"
            >{{ (row.prtcnt == 0 || !row.prtcnt) ? "打印" : "已打印" }}</el-button
          >
        </template>
      </el-table-column>
      <!-- <el-table-column
        v-if="filtrateList.includes('dicomurl')"
        prop="dicomurl"
        min-width="120px"
        label="常规报告"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span @click="regularInfo(row)" style="cursor: pointer"
            ><el-icon :style="{ color: row.pdfUrl ? '#409eff' : '' }"
              ><Document /></el-icon
          ></span>
        </template>
      </el-table-column> -->
      <el-table-column
        v-if="filtrateList.includes('checkTime')"
        min-width="160px"
        prop="checkTime1"
        label="检查时间"
        align="center"
      >
        <template #default="{ row }">
          <span>{{
            row.checkTime1 ? row.checkTime1 : "----/--/-- --:--:--"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('docname')"
        prop="docname"
        min-width="100px"
        label="检查医师"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('reportTime')"
        prop="reportTime1"
        min-width="160px"
        label="报告时间"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('reportDoctor')"
        prop="reportDocname"
        min-width="160px"
        label="报告医师"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('qualityTime')"
        prop="uploadTime1"
        min-width="160px"
        label="质控日期"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('medicalRecordID')"
        prop="medicalRecordID"
        min-width="170px"
        label="病历记录ID"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('devid')"
        prop="devid"
        min-width="120px"
        label="设备SN"
        align="center"
      />
    </el-table>
    <el-pagination
      v-model:current-page="pageList.current"
      v-model:page-size="pageList.size"
      :page-sizes="[20, 40, 60, 80]"
      small="small"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageList.total"
      class="pagination-css"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      title="常规报告"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="960px"
    >
      <!-- <iframe :src="imgUrl" style="width: 100%; height: 600px"></iframe> -->
      <iframe id="iframePdf" :src="pdfInfo.pdfUrl + '#toolbar=0'" style="width: 100%; height: 600px"></iframe>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="pdfInfo.operateType == '打印'" type="primary" @click="printPdf">打印</el-button>
          <el-button v-if="pdfInfo.operateType == '下载'" type="primary" @click="downloadPdf">下载PDF文件并关闭窗口</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getUltraSoundList } from "@/apis/reportReview";
import format from "@/utils/format";
import { ElMessage } from "element-plus";
import JSZip from "jszip";
// import JSZipUtils from "jszip-utils";
import { saveAs } from 'file-saver';
import { prtsn } from "@/apis/user";

import { getUserOrganNameList } from "@/apis/reportStatistics";
export default {
  data() {
    let nowTime = new Date().getTime();
    let stime = format(nowTime, "YYYY-MM-DD") + " " + "23:59:59";
    let etime = format(nowTime, "YYYY-MM-DD") + " " + "00:00:00";
    return {
      organNameList: [],
      selectedItems: [], // 保存用户勾选的项目
      roleInfo: "",
      fullscreenLoading: false,
      json_fields: {
        序号: {
          field: "index",
          callback: (value) => {
            return String(value);
          },
        },
        条码: {
          field: "t_sn",
          callback: (value) => {
            return String(value);
          },
        },
        项目点名称: {
          field: "insname",
          callback: (value) => {
            return String(value);
          },
        },
        姓名: {
          field: "name",
          callback: (value) => {
            return String(value);
          },
        },
        性别: {
          field: "sex",
          callback: (value) => {
            return String(value);
          },
        },
        年龄: {
          field: "age",
          callback: (value) => {
            return String(value);
          },
        },
        联系电话: {
          field: "tel",
          callback: (value) => {
            return String(value);
          },
        },
        诊断结论: {
          field: "diagnostic",
          callback: (value) => {
            return String(value);
          },
        },
        是否阳性: {
          field: "isPositiveText",
          callback: (value) => {
            return String(value);
          },
        },
        是否有效: {
          field: "isInvalidText",
          callback: (value) => {
            return String(value);
          },
        },
        无效原因: {
          field: "invalidReason",
          callback: (value) => {
            return String(value);
          },
        },

        设备名称: {
          field: "devname",
          callback: (value) => {
            return String(value);
          },
        },
        报告状态: {
          field: "auditText",
          callback: (value) => {
            return String(value);
          },
        },

        检查时间: {
          field: "checkTime1",
          callback: (value) => {
            return String(value);
          },
        },

        检查医师: {
          field: "docname",
          callback: (value) => {
            return String(value);
          },
        },
        报告时间: {
          field: "reportTime1",
          callback: (value) => {
            return String(value);
          },
        },
        报告医师: {
          field: "reportDoctor",
          callback: (value) => {
            return String(value);
          },
        },
        质控日期: {
          field: "uploadTime1",
          callback: (value) => {
            return String(value);
          },
        },
        病历记录ID: {
          field: "medicalRecordID",
          callback: (value) => {
            return String(value);
          },
        },
        设备SN: {
          field: "devid",
          callback: (value) => {
            return String(value);
          },
        },
      },
      userExcelName: "",
      dialogVisible: false,
      pdfInfo: null,
      formInline: {
        keyword: "",
        inspectionTime: [stime, etime],
        reportTime: [],
        qualityTime: [],
        projectName: "",
        inspectDoctor: "",
        reportDoctor: "",
        reportStatus: "",
        isUsed: "",
      },
      filtrateList: [
        "devid",
        "devname",
        "name",
        "sex",
        "age",
        "tel",
        "checkTime",
        "insname",
        "docname",
        "reportTime",
        "reportDoctor",
        "qualityTime",
        "medicalRecordID",
        "diagnostic",
        "isPositive",
        "isInvalid",
        "invalidReason",
        "auditstatus",
        "dicomurl",
      ],
      tableData: [],
      selectedItems: [], // 保存用户勾选的项目
  
      tableLoading: false,
      selectedRows: [], // 选中的行数据9月25号
      pageList: {
        current: 1,
        size: 20,
        total: 0,
      },
      statusList: [
        {
          label: "发送失败",
          value: "12",
        },
        {
          label: "发送成功",
          value: "11",
        },
      ],
      isUsedList: [
        {
          label: "无效",
          value: "1",
        },
        {
          label: "有效",
          value: "0",
        },
      ],
      isPositiveList: [
        {
          label: "阳性",
          value: "1",
        },
        {
          label: "阴性",
          value: "0",
        },
      ],
    };
  },
  mounted() {
    this.getUserOrganName()
    this.getTableData();//9月25号增加的这行
    let gyPoint = localStorage.getItem("gyPoint");
    if (gyPoint) {
      this.filtrateList = JSON.parse(gyPoint);
    }
    this.init();
    this.saveCookie();
    this.roleInfo = this.$store.getters.role ? this.$store.getters.role : "";
  },
  methods: {
    getUserOrganName() {
      this.organNameList = []
      getUserOrganNameList({
        uname: this.$store.getters.name,
      }).then((result) => {
        this.organNameList = result.data;
      });
    },
    downloadPdf() {
      let link = document.createElement('a')
      let _this = this
      this.fetchPDFThroughProxy(this.pdfInfo.pdfUrl).then(blob => {
        link.href = URL.createObjectURL(blob)
        link.download = (this.pdfInfo.name ? (this.pdfInfo.name + '_') : '') + (this.pdfInfo.age ? (this.pdfInfo.age + '_') : '') + (this.pdfInfo.t_sn ? this.pdfInfo.t_sn : '')
        // link.download = (this.pdfInfo.t_sn ? this.pdfInfo.t_sn : '') + (this.pdfInfo.name ? this.pdfInfo.name : '')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.dialogVisible = false
        _this.isDwn()
      })
    },
    printPdf() {
      let link = document.createElement('iframe')
      let _this = this
      this.fetchPDFThroughProxy(this.pdfInfo.pdfUrl).then(blob => {
        link.style.display = 'none'
        let idNum = 'printPdf' + new Date().getTime()
        link.setAttribute('id', idNum)
        link.src = URL.createObjectURL(blob)
        document.body.appendChild(link)
        let iframePdf = document.getElementById(idNum).contentWindow
        iframePdf.print()
        window.URL.revokeObjectURL(link.src)
        this.dialogVisible = false
        this.isPrint()
      })
    },
    isPrint() {
      prtsn({
        type: "ultrasound",
        action: "print",
        sn: this.pdfInfo.t_sn,
        uname: this.$store.getters.name,
      }).then((res) => {
        if (res.data.status == "00") {
          this.getTableData();
        }
      });
    },
    isDwn() {
      prtsn({
        type: "ultrasound",
        action: "download",
        sn: this.pdfInfo.t_sn,
        uname: this.$store.getters.name,
      }).then((res) => {
        if (res.data.status == "00") {
          this.getTableData();
        }
      });
    },
    // 通过代理下载 PDF 文件
    fetchPDFThroughProxy(url) {
      const baseURL = "http://cvd.cdhyhs.com/pdf/";
      const cleanUrl = url.replace("https://ultrasound.cdhyhs.com/", "");
        // const proxyUrl = baseURL + cleanUrl;
        const proxyUrl = url;

      return fetch(proxyUrl)
        .then((response) => {
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          return response.blob();
        })
        .catch((error) => {
          console.error("Error fetching PDF:", error);
          throw error;
        });
    },
    saveCookie() {
      let gyPoint = JSON.stringify(this.filtrateList);
      localStorage.setItem("gyPoint", gyPoint);
    },
    changeBox() {
      let gyPoint = JSON.stringify(this.filtrateList);
      localStorage.setItem("gyPoint", gyPoint);
    },
    async downloadEx() {
      let insTitle = this.$store.getters.insname
        ? this.$store.getters.insname
        : "";
      let inspecSTime = "";
      let inspecETime = "";
      let data = [];
      this.fullscreenLoading = true;
      if (
        this.formInline.inspectionTime &&
        this.formInline.inspectionTime.length > 0
      ) {
        inspecSTime = this.formInline.inspectionTime[0];
        inspecETime = this.formInline.inspectionTime[1];
        this.userExcelName =
          insTitle + "_超声报告列表_" + inspecSTime + "~" + inspecETime;
        let res = await getUltraSoundList({
          page: 1, // 当前页
          size: 10000, // 每页size
          uname: this.$store.getters.name, // 登录用户
          insname: this.$store.getters.insname, //用户机构名
          keyword: this.formInline.keyword ? this.formInline.keyword : "", // 关键字
          inspectionStime: this.formInline.inspectionTime
            ? this.formInline.inspectionTime[0]
              ? this.formInline.inspectionTime[0]
              : ""
            : "", // 检查开始时间
          inspectionEtime: this.formInline.inspectionTime
            ? this.formInline.inspectionTime[1]
              ? this.formInline.inspectionTime[1]
              : ""
            : "", // 检查结束时间
          qualityStime: this.formInline.qualityTime
            ? this.formInline.qualityTime[0]
              ? this.formInline.qualityTime[0]
              : ""
            : "", //质控开始时间
          qualityEtime: this.formInline.qualityTime
            ? this.formInline.qualityTime[1]
              ? this.formInline.qualityTime[1]
              : ""
            : "", //质控结束时间
          reportStime: this.formInline.reportTime
            ? this.formInline.reportTime[0]
              ? this.formInline.reportTime[0]
              : ""
            : "", //报告开始时间
          reportEtime: this.formInline.reportTime
            ? this.formInline.reportTime[1]
              ? this.formInline.reportTime[1]
              : ""
            : "", //报告结束时间
          projectName: this.formInline.projectName
            ? this.formInline.projectName
            : "", //项目点名称

          inspectDoctor: this.formInline.inspectDoctor
            ? this.formInline.inspectDoctor
            : "", //检查医师
          reportDoctor: this.formInline.reportDoctor
            ? this.formInline.reportDoctor
            : "", //报告医师

          reportStatus: this.formInline.reportStatus
            ? this.formInline.reportStatus
            : "", //报告状态
          // isvalid: this.formInline.isUsed ? this.formInline.isUsed : "", // 是否有效
          project: "心血管研究院",
          isInvalid: this.formInline.isInvalid,
          isPositive: this.formInline.isPositive,
        });
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            res.data.forEach((el, index) => {
              let auditText = "";
              el.index = index + 1;
              if (el.auditstatus == 11) {
                auditText = "发送成功";
              } else if (el.auditstatus == 12) {
                auditText = "发送失败";
              }
              el.auditText = auditText;
              el.isInvalidText = el.isInvalid == 0 ? "有效" : "无效";
              el.isPositiveText =
                el.isPositive == "1"
                  ? "阳性"
                  : el.isPositive == "0"
                  ? "阴性"
                  : "";
              if (el.checkTime > 0) {
                el.checkTime1 = format(
                  el.checkTime * 1000,
                  "YYYY-MM-DD HH:mm:ss"
                );
              } else {
                el.checkTime1 = "";
              }
              el.reportTime1 = format(
                el.reportTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.uploadTime1 = format(
                el.uploadTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.medicalRecordID = "";
              el.diagnostic = el.diagnosis ? el.diagnosis : "";
              if (el.json) {
                let jsonData = JSON.parse(el.json.replace(/'/g, '"'));
                el.medicalRecordID = jsonData
                  ? jsonData.mrid
                    ? jsonData.mrid
                    : el.c_sn
                  : el.c_sn;
              } else {
                el.medicalRecordID = el.c_sn ? el.c_sn : "";
              }
            });
            data = res.data;
          }
        }
        this.fullscreenLoading = false;
        return data;
      } else {
        ElMessage({
          message: "请选择检查时间",
          type: "warning",
        });
        this.fullscreenLoading = false;
        return data;
      }
    },
    init() {
      this.getTableData();
    },
    regularInfo(row) {
      // if (row.auditstatus == 10) {
        console.log(row, "row");
        row.operateType = "下载";
        this.pdfInfo = {};
        this.pdfInfo = row;
        if (row.vender == '非雀医疗') {
          indication = JSON.parse(row.origjson).Description.split('\n')
        } else if (row.vender == '飞依诺') {
          indication = JSON.parse(row.origjson).Summary.split('\r\n')
        }
        this.pdfInfo.indication = indication
        this.dialogVisible = true;
      // } else {
      //   ElMessage({
      //     type: "warning",
      //     message: "报告未审核，请等待审核通过后查看",
      //   });
      // }
    },
    printInfo(row) {
      // if (row.auditstatus == 10) {
        console.log(row, "row");
        row.operateType = "打印";
        this.pdfInfo = {};
        this.pdfInfo = row;
        if (row.vender == '非雀医疗') {
          indication = JSON.parse(row.origjson).Description.split('\n')
        } else if (row.vender == '飞依诺') {
          indication = JSON.parse(row.origjson).Summary.split('\r\n')
        }
        this.pdfInfo.indication = indication
        this.dialogVisible = true;
      // } else {
      //   ElMessage({
      //     type: "warning",
      //     message: "报告未审核，请等待审核通过后查看",
      //   });
      // }
    },
    // regularInfo(row) {
    //   this.imgUrl = "";
    //   if (row.pdfUrl) {
    //     this.imgUrl = row.pdfUrl;
    //     this.dialogVisible = true;
    //   } else {
    //     ElMessage({
    //       message: "暂无报告",
    //       type: "warning",
    //     });
    //   }
    // },
    // getTableData() {9月25号
    //   this.tableLoading = true;
    //   this.tableData = [];
    // 动态获取表格数据这个是9月25号新加的
    async getTableData() {
      try {
        const res = await getUltraSoundList({ page: 1, size: 100 }); // 调用 API 获取 PDF 列表
        if (res.code === 0) {
          this.tableData = res.data.map((item) => ({
            name: item.projectName,  // 动态获取的项目名称
            pdfUrl: item.pdfUrl,     // 动态获取的 PDF URL
          }));
        }
      } catch (error) {
        console.error("获取表格数据失败", error);
        this.$message.error("获取表格数据失败，请稍后重试");
      }
    
      getUltraSoundList({
        page: this.pageList.current, // 当前页
        size: this.pageList.size, // 每页size
        uname: this.$store.getters.name, // 登录用户
        insname: this.$store.getters.insname, //用户机构名
        keyword: this.formInline.keyword ? this.formInline.keyword : "", // 关键字
        inspectionStime: this.formInline.inspectionTime
          ? this.formInline.inspectionTime[0]
            ? this.formInline.inspectionTime[0]
            : ""
          : "", // 检查开始时间
        inspectionEtime: this.formInline.inspectionTime
          ? this.formInline.inspectionTime[1]
            ? this.formInline.inspectionTime[1]
            : ""
          : "", // 检查结束时间
        qualityStime: this.formInline.qualityTime
          ? this.formInline.qualityTime[0]
            ? this.formInline.qualityTime[0]
            : ""
          : "", //质控开始时间
        qualityEtime: this.formInline.qualityTime
          ? this.formInline.qualityTime[1]
            ? this.formInline.qualityTime[1]
            : ""
          : "", //质控结束时间
        reportStime: this.formInline.reportTime
          ? this.formInline.reportTime[0]
            ? this.formInline.reportTime[0]
            : ""
          : "", //报告开始时间
        reportEtime: this.formInline.reportTime
          ? this.formInline.reportTime[1]
            ? this.formInline.reportTime[1]
            : ""
          : "", //报告结束时间
        projectName: this.formInline.projectName
          ? this.formInline.projectName
          : "", //项目点名称

        inspectDoctor: this.formInline.inspectDoctor
          ? this.formInline.inspectDoctor
          : "", //检查医师
        reportDoctor: this.formInline.reportDoctor
          ? this.formInline.reportDoctor
          : "", //报告医师

        reportStatus: this.formInline.reportStatus
          ? this.formInline.reportStatus
          : "", //报告状态
        // isvalid: this.formInline.isUsed ? this.formInline.isUsed : "", // 是否有效
        project: "心血管研究院",
        isInvalid: this.formInline.isInvalid,
        isPositive: this.formInline.isPositive,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data || [];
          this.pageList.total = res.size;
          //上面2行新加代码9月25号
          if (res.data && res.data.length > 0) {
            res.data.forEach((el) => {
              el.checkTime1 = format(
                el.checkTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.reportTime1 = format(
                el.reportTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.uploadTime1 = format(
                el.uploadTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.medicalRecordID = "";
              el.diagnostic = el.diagnosis ? el.diagnosis : "";
              if (el.json) {
                let jsonData = JSON.parse(el.json.replace(/'/g, '"'));
                el.medicalRecordID = jsonData
                  ? jsonData.mrid
                    ? jsonData.mrid
                    : el.c_sn
                  : el.c_sn;
              } else {
                el.medicalRecordID = el.c_sn ? el.c_sn : "";
              }
            });
            this.tableData = res.data;
          }
          this.pageList.total = res.size;
          this.tableLoading = false;
        }
      });
    },
    // 搜索
    search() {
      this.pageList.current = 1;
      this.getTableData();
    },
    // 重置
    reset() {
      let nowTime = new Date().getTime();
      let stime = format(nowTime, "YYYY-MM-DD") + " " + "23:59:59";
      let etime = format(nowTime, "YYYY-MM-DD") + " " + "00:00:00";
      this.pageList.current = 1;
      this.formInline.keyword = "";
      this.formInline.inspectionTime = [stime, etime];
      this.formInline.reportTime = [];
      this.formInline.qualityTime = [];
      this.formInline.projectName = "";
      this.formInline.inspectDoctor = "";
      this.formInline.isInvalid = "";
      this.formInline.isPositive = "";
      this.formInline.reportDoctor = "";
      this.formInline.reportStatus = "";
      this.formInline.isUsed = "";
      this.init();
      //9月25号增加下面2行
      this.pageList.current = 1;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.pageList.current = 1;
      this.pageList.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.pageList.current = val;
      this.getTableData();
    },
    //下面是9月25号增加代码
     // 处理用户勾选的项目
    handleSelectionChange(val) {
      this.selectedItems = val;
    },

    // 批量导出 PDF 并打包为 ZIP
    async exportSelectedPDFs() {
    if (this.selectedItems.length === 0) {
      this.$message.warning("请先选择要导出的报告");
      return;
    }

    const zip = new JSZip();
    const zipFolder = zip.folder("超声报告");

    const downloadPromises = this.selectedItems.map((item, index) => {
      // 调用代理 API 下载 PDF
      return this.fetchPDFThroughProxy(item.pdfUrl).then((pdfBlob) => {
        zipFolder.file(`report_${index + 1}.pdf`, pdfBlob);
      });
    });

    try {
      await Promise.all(downloadPromises);

      // 生成 ZIP 文件并下载
      zip.generateAsync({ type: "blob" }).then((blob) => {
        saveAs(blob, `项目超声报告_${this.selectedItems.length}份.zip`);
      });
    } catch (error) {
      console.error("批量导出失败", error);
      this.$message.error("导出过程中出错，请稍后重试");
    }
  },

  fetchPDFThroughProxy(url) {
    const proxy/Url = '/pdf' + url.split('ultrasound.cdhyhs.com')[1];
      // const proxyUrl = baseURL + cleanUrl;
      const proxyUrl = url;
    return fetch(proxyUrl)
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.blob();
      })
      .catch(error => {
        console.error('Error fetching PDF:', error);
        throw error;
      });
    },
  },
};
</script>